package com.syp.auth.export.common;

import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public final class TokenCooikeMaster {

	private static final TokenCooikeMaster instunce = new TokenCooikeMaster();

	private TokenCooikeMaster() {
		//
	}

	public static TokenCooikeMaster getInstunce() {
		return TokenCooikeMaster.instunce;
	}

	/**
	 * 获取token
	 * @param request
	 * @return
	 */
	public Cookie get(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		Cookie token = null;
		if(cookies != null){
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(GorgeousParameters.AUTH_COOKIE_NAME)) {
					token = cookie;
				}
			}
		}

		return token;
	}

	/**
	 * 写入token cookie
	 * @param response
	 * @return
	 */
	public Cookie put(HttpServletResponse response) {
		String value = TokenSecurity.getInstunce().encrypt(UUID.randomUUID().toString());
		Cookie token = new Cookie(GorgeousParameters.AUTH_COOKIE_NAME, value);
		token.setPath("/");
		int timeout = GorgeousParameters.TOKEN_EXISTS_HOURS * 60 * 60;
		token.setMaxAge(timeout);
		response.addCookie(token);

		return token;
	}
	
	/**
	 * 清除登录认证cookie
	 * @param request
	 * @param response
	 * @return
	 */
	public Cookie remove(HttpServletRequest request, HttpServletResponse response) {
		Cookie[] cookies = request.getCookies();
		Cookie token = null;
		for (Cookie cookie : cookies) {
			if (cookie.getName().equals(GorgeousParameters.AUTH_COOKIE_NAME)) {
				token = cookie;
			}
		}
		
		if (token != null) {
			Cookie nullToken =  new Cookie(token.getName(), null);
			nullToken.setPath("/");
			response.addCookie(nullToken);
		}		
		return token;
		
	}
}
